package com.css.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AES256Utils {
    private static final String ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
    private static final int KEY_SIZE = 256;
    private static final int GCM_IV_LENGTH = 12;
    private static final int GCM_TAG_LENGTH = 16;

    /**
     * 生成一个随机的 256 位 AES 密钥。
     *
     * @return Base64 编码的密钥字符串。
     * @throws NoSuchAlgorithmException 如果 AES 算法不可用。
     */
    public static String generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE, new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * 加密数据。
     *
     * @param plaintext 要加密的明文。
     * @param keyBase64 Base64 编码的密钥。
     * @return Base64 编码的密文，包含 IV 和加密后的数据。
     * @throws Exception 加密过程中发生的任何异常。
     */
    public static String encrypt(String plaintext, String keyBase64) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(keyBase64);
        SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        // 生成随机的 IV (Initialization Vector)
        byte[] iv = new byte[GCM_IV_LENGTH];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

        byte[] ciphertextBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

        // 将 IV 和密文合并后进行 Base64 编码
        ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + ciphertextBytes.length);
        byteBuffer.put(iv);
        byteBuffer.put(ciphertextBytes);
        return Base64.getEncoder().encodeToString(byteBuffer.array());
    }

    /**
     * 解密数据。
     *
     * @param ciphertextBase64 Base64 编码的密文，包含 IV 和加密后的数据。
     * @param keyBase64        Base64 编码的密钥。
     * @return 解密后的明文。
     * @throws Exception 解密过程中发生的任何异常。
     */
    public static String decrypt(String ciphertextBase64, String keyBase64) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(keyBase64);
        SecretKey secretKey = new SecretKeySpec(keyBytes, ALGORITHM);

        byte[] ciphertextAndIvBytes = Base64.getDecoder().decode(ciphertextBase64);

        // 从密文中分离 IV 和密文
        ByteBuffer byteBuffer = ByteBuffer.wrap(ciphertextAndIvBytes);
        byte[] iv = new byte[GCM_IV_LENGTH];
        byteBuffer.get(iv);
        byte[] ciphertextBytes = new byte[byteBuffer.remaining()];
        byteBuffer.get(ciphertextBytes);

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec);

        byte[] plaintextBytes = cipher.doFinal(ciphertextBytes);
        return new String(plaintextBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String key = generateKey();
        System.out.println("Generated Key (Base64): " + key);

        String plaintext = "This is a secret message!";
        System.out.println("Plaintext: " + plaintext);

        String ciphertext = encrypt(plaintext, key);
        System.out.println("Ciphertext (Base64): " + ciphertext);

        String decryptedText = decrypt(ciphertext, key);
        System.out.println("Decrypted Text: " + decryptedText);

        String anotherPlaintext = "Another confidential data.";
        String anotherCiphertext = encrypt(anotherPlaintext, key);
        System.out.println("Another Ciphertext (Base64): " + anotherCiphertext);
        String anotherDecryptedText = decrypt(anotherCiphertext, key);
        System.out.println("Another Decrypted Text: " + anotherDecryptedText);
    }
}
